import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getNotes, getNote, createNote, updateNote, deleteNote, searchNotes } from '@/api/notes'
import { ElMessage } from 'element-plus'

export const useNoteStore = defineStore('note', () => {
  const notes = ref([])
  const currentNote = ref(null)
  const total = ref(0)
  const loading = ref(false)
  const searchResults = ref([])

  // 获取笔记列表
  async function fetchNotes(params = {}) {
    loading.value = true
    try {
      const data = await getNotes(params)
      notes.value = data.notes
      total.value = data.total
    } catch (error) {
      ElMessage.error('获取笔记列表失败')
    } finally {
      loading.value = false
    }
  }

  // 获取笔记详情
  async function fetchNote(id) {
    loading.value = true
    try {
      currentNote.value = await getNote(id)
      return currentNote.value
    } catch (error) {
      ElMessage.error('获取笔记详情失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 创建笔记
  async function addNote(noteData) {
    try {
      const note = await createNote(noteData)
      notes.value.unshift(note)
      total.value++
      ElMessage.success('笔记创建成功')
      return note
    } catch (error) {
      ElMessage.error('创建笔记失败')
      throw error
    }
  }

  // 更新笔记
  async function modifyNote(id, noteData) {
    try {
      const note = await updateNote(id, noteData)
      const index = notes.value.findIndex(n => n.id === id)
      if (index !== -1) {
        notes.value[index] = note
      }
      if (currentNote.value?.id === id) {
        currentNote.value = note
      }
      ElMessage.success('笔记更新成功')
      return note
    } catch (error) {
      ElMessage.error('更新笔记失败')
      throw error
    }
  }

  // 删除笔记
  async function removeNote(id) {
    try {
      await deleteNote(id)
      notes.value = notes.value.filter(n => n.id !== id)
      total.value--
      ElMessage.success('笔记已删除')
    } catch (error) {
      ElMessage.error('删除笔记失败')
      throw error
    }
  }

  // 搜索笔记
  async function search(keyword) {
    if (!keyword.trim()) {
      searchResults.value = []
      return
    }
    
    loading.value = true
    try {
      searchResults.value = await searchNotes(keyword)
    } catch (error) {
      ElMessage.error('搜索失败')
    } finally {
      loading.value = false
    }
  }

  // 清空当前笔记
  function clearCurrentNote() {
    currentNote.value = null
  }

  return {
    notes,
    currentNote,
    total,
    loading,
    searchResults,
    fetchNotes,
    fetchNote,
    addNote,
    modifyNote,
    removeNote,
    search,
    clearCurrentNote
  }
})

